import 'global/axios.min.js';
import {alert} from '../bi-plug/plug.js';
/**
 * Ajax 请求
 * @param {object} config  配置
 * @param {string} config.url 请求地址
 * @param {object} config.data 请求参数
 * @param {function} config.success 成功回调
 * @param {function} [config.fail] 失败回调
 * @param {function} [config.over] 完成回调
 * @param {string} [config.method]  GET|POST|PUT|DELETE 请求方式
 * @returns 
 * 
 */
function ajax(config){
        
    if (config==undefined) return null;

    if (config['method']==undefined) config['method']= 'post';

    let success = ()=>{};
    
    if (config['success']!=undefined){
        success =  config['success'];
        delete config['success'];
    }

    let over = ()=>{

    }

    if (config['over']!=undefined){
        if ( typeof(config['over'])=='function') over =  config['over'];
        delete config['over'];
    }
    //默认错误处理
    let fail= (msg,data)=>{
        alert({text:msg,type:'error',icon:'fa fa-globe'});
        console.log(msg);
        console.log(config);
        console.log(data);
    };

    
    if (config['fail']!=undefined){
        if ( typeof(config['fail'])=='function') fail =  config['fail'];
        delete config['fail'];
    }


    //config['url'] = this.baseURL+config['url'];

    let  options = {
        timeout: 1000*30,
        headers:{'Content-Type': 'multipart/form-data','X-Requested-With': 'XMLHttpRequest'}
    };

   
    if (config['data']!=undefined){
        
        let formdata = new FormData();   

        let stringifyFormData = (name,data)=>{
            if (typeof(data)=='object' &&  data!=null){
                if (data.constructor == Array){

                    for(let i in data){
                        stringifyFormData(name+'['+i+']',data[i]);
                    }

                }

                if (data.constructor == Object){

                    for(let i in data){
                        if (name!='') stringifyFormData(name+'['+i+']',data[i]);
                        else stringifyFormData(i,data[i]);
                    }

                }

            }else{
               if (data!=null) formdata.append(name,data);
            }

        }
        stringifyFormData('',config['data'] );
        config['data'] =  formdata;
    }

     

    let ajax = axios.create(options);

    //如果没有设置返回函数，就返回ajax对象
    
    if (typeof success == 'function'){
        ajax(config).then((res)=>{

            if (res.status == 200){

               let  re = res.data;
               //Login 
               if (typeof(re)!="object" ) {
                    fail('返回错误','返回数据格式错误',re);
                    over();
                    return ;
                }

                if (re['status']==undefined){
                    fail('返回错误','status未定义');
                    over();
                    return ;
                }

                switch(re['status']){
                    case 'success':


                        /*

                        
                        if (re['data']){
                            fail('返回错误','data未定义');
                            over();
                            return ;
                        }
                            
                        if (typeof(re['data'])!="object" || re['data'] !=null || re['data'] !=true){
                            fail('返回错误','data格式错误',re['data']);
                            over();
                            return ;
                        }
                        */

                        try{
                            success(re['data']);
                        }catch(e){
                             
                            console.log(e);
                        }
                        
                       
                    break;

                    case 'fail':
                        fail(re.msg,re);
                    break;

                    case 'error':
                        fail(re.msg,re);
                    break;

                    default:
                        fail('状态错误',re.status,re);
                    break;
                }

                over();
            
            }

            if (res.status == 404){
                fail('404',"未找到请求的地址");
            }

        }).catch(()=>{

            let msg =  '连接服务器失败，请重试或者联系管理员';
            //if (loading) _loading.close();
            fail('网络错误',msg);
            over();
        });
    }else{
        return ajax(config);
    }


   
}

function assign  (oldData,newData,add=false){
    if (typeof(oldData)!='object') return oldData;
  
    for(let key in newData){
        if (oldData[key]!=undefined){
            oldData[key] = newData[key];
        }else{
            if (add) oldData[key] = newData[key];
        }
    }
    
    return oldData;
  }



function uploadFile(url,file,params,success,over){
    let param = new FormData()       // 创建form对象     
    param.append('file', file)       // 通过append向form对象添加数据
    //param.append("需要接受的数据名", "数据"); // 添加form表单中其他数据
    //let _config =JSON.parse(JSON.stringify(config.ajax));
    
    for(let key in params ){
        param.append(key, params[key]);
    }

    let  options = {
        baseURL: this.baseURL,
        timeout: 1000*30,
        headers:{'Content-Type': 'multipart/form-data','X-Requested-With': 'XMLHttpRequest'}
    };

    if (typeof over != 'function'){
        over = ()=>{};
    }

    //默认错误处理
    let fail= (msg,data)=>{
        alert({text:msg,type:'error',icon:'fa fa-globe'});
        console.log(msg);
        //console.log(config);
        console.log(data);
    };
    
    axios.post(url,param, options).then((res)=>{
        
       
        if (res.status == 200){

            let  re = res.data;
            //Login 
            if (typeof(re)!="object" ) {
                 fail('返回错误','返回数据格式错误',re);
                 over();
                 return ;
             }

             if (re['status']==undefined){
                 fail('返回错误','status未定义');
                 over();
                 return ;
             }

             switch(re['status']){
                 case 'success':

                     if (re['data']==undefined){
                         fail('返回错误','data未定义');
                         over();
                         return ;
                     }

                     if (typeof(re['data'])!="object"){
                         fail('返回错误','data格式错误',re['data']);
                         over();
                         return ;
                     }
                     try{
                         success(re['data']['url']);
                     }catch(e){
                         console.log(e);
                     }
                     
                    
                 break;

                 case 'fail':
                     fail(re.msg,re);
                 break;

                 case 'error':
                     fail(re.msg,re);
                 break;

                 default:
                     fail('状态错误',re.status,re);
                 break;
             }

             over();
         
         }

         if (res.status == 404){
             fail('404',"未找到请求的地址");
             over();
         }

    }).catch((err)=>{
        console.log(err);
        fail('上传服务器失败');
        over();
    });
}

  /**
  * 防抖函数
  * 
  * @param {function} callback 
  * @param {number} delay 
  * @returns 
  */
  function debounce(callback, delay) {
    let timer = null
  
  // 所以这个函数就可以使用...运算符收集js自动添加的参数到一个数组中
    return function _debounce(...arg) {
      if (timer) clearTimeout(timer)
      timer = setTimeout(() => {
        // 通过apply绑定this和传递参数，apply第二个参数正好是传数组嘛
        callback.apply(this, arg)
      }, delay)
    }
  }

 /**
  * 动态加载js文件
  * 
  * @param {string} url 动态加载js文件路径
  * @param {funtion} callback 加载完js文件之后的回调
  * @param {string} id 动态加载js文件的script标签的id
  * @param {object} parent 动态加载js文件的script标签放在哪个父元素下，默认值为document.body
  */
 function loadScript(url, callback, id, parent) {
    let parentDom = document.body
    parent && (parentDom = parent)
    if (id && parentDom.querySelector(`#${id}`)) {
      callback && callback()
    } else {
      var script = document.createElement('script')
      script.type = 'text/javascript'
      script.async = 'async'
      script.src = url
      id && (script.id = id)
      parentDom.appendChild(script)
      if (script.readyState) {   //IE
        script.onreadystatechange = function() {
          if (script.readyState == 'complete' || script.readyState == 'loaded') {
            script.onreadystatechange = null
            callback && callback()
          }
        }
      } else {    // 非IE
        script.onload = function() {
          callback && callback()
        }
      }
    }
    }



export default {
    ajax,assign,uploadFile,debounce,loadScript
}